<template>
  <div id="container" class="map-container" ref="mapContainer">
    <div class="ledgend-heat" v-if="this.$route.path=='/MultipleIndicators'">
      <div class="ledgend-heat-item" v-for="item in heatLegend" :key="item.name">
        <div class="ledgend-heat-item-text" :style="'background-color:' +item.color">{{item.name}}</div>
<!--        <span class="ledgend-heat-item-color">{{item.color}}</span>-->
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import {EventBus} from "../utils/event-bus";
let that;
export default {
  name: 'AMapContainer',
  inject: ['imgUrl'], // 注入公共变量
  data() {
    return {
      rarePlantList:[],
      rarePlantZIndex:1,
      polygonList:[],
      textList:[],
      heatLegend:[
      ],
      // imageUrls : [
      //   'http://111.229.223.177:9098/bg.png',
      //   'http://111.229.223.177:9098/bg.png',
      //   'http://111.229.223.177:9098/bg.png',
      //   'http://111.229.223.177:9098/bg.png',
      //   'http://111.229.223.177:9098/bg.png',
      //   'http://111.229.223.177:9098/bg.png',
      // ],
      popups:[],
      identifyList:[],
      identifyImageList:[],
      infoWindows:[],
      map: null,
      heatmap: null,
      selectId:null,
      polylines:[],
      markerList: [],
      deviceList:[],
      doorList:[
        {
          lonGd:121.439587,
          latGd:31.142106,
          localName:'3号门',
          icon:require(`@/assets/img/door.png`)
        },
        {
          lonGd:121.450931,
          latGd:31.14994,
          localName:'2号门',
          icon:require(`@/assets/img/door.png`)
        },
        {
          lonGd:121.438249,
          latGd:31.145404,
          localName:'6号门',
          icon:require(`@/assets/img/door.png`)
        },
        {
          lonGd:121.445702,
          latGd:31.152127,
          localName:'4号门',
          icon:require(`@/assets/img/door.png`)
        },
        {
          lonGd:121.450992,
          latGd:31.146399,
          localName:'1号门',
          icon:require(`@/assets/img/door.png`)
        }
      ],
      position:{lon:121.444515, lat:31.145246,zoom:16.35}
    }
  },
  created() {
    that=this;
    EventBus.$on('clear-identify', (message) => {
      this.clearIdentify();
    });
    EventBus.$on('add-identify', (message) => {
      if(message){
        if (message.length>0){
          this.identifyImageList=this.identifyImageList.concat(message);
        }
      }
    });
    EventBus.$on('showRarePlant', (message) => {
      this.showRarePlant(message);
    });
    EventBus.$on('sent-device-id-to-right', (message) => {
      this.setSelect(message.id);
    });
    EventBus.$on('set-markers-without-title', (message) => {
      this.addMarkersWithOutTitle(message)
    });
    EventBus.$on('sent-heat-map-data', (message) => {
      console.log(this.heatmap.config.gradient);
      this.heatLegend=[];
      if(message==null||message==[]){
        message={data:[],max:0}
      }
      this.heatmap.setDataSet(message);
      if(message.max&&message.max>0){
        this.initLegend(this.heatmap.config.gradient,message.max);
      }
    });
    EventBus.$on('set-markers', (message) => {
      this.addMarkers(message)
    });
    EventBus.$on('set-polygons', (message) => {
      this.addPolygon(message)
    });
    EventBus.$on('set-position', (message) => {
      this.setMapPosition(message)
    });
    EventBus.$on('set-lines', (message) => {
      this.updateLines(message);
    });
    EventBus.$on('setMapPosition', (message) => {
      this.setMapPosition(message);
    });
  },
  computed: {
    mapMarkers() {
      return this.$store.state.map.markers
    },
    currentDeviceType() {
      return this.$store.state.map.currentDeviceType
    }
  },
  watch: {
    mapMarkers: {
      handler(newMarkers) {
        if (!this.map) return;
        
        // 清除现有标注
        if (this.markerList.length > 0) {
          this.map.remove(this.markerList);
        }
        if (this.infoWindows.length > 0) {
          this.infoWindows.forEach(function(currentValue, index) {
            if(currentValue.getIsOpen()){
              currentValue.close();
            }
          });
        }
        this.infoWindows=[];
        this.markerList = [];
        this.deviceList = newMarkers;
        // 添加新标注
        newMarkers.forEach(markerData => {
          const marker = new AMap.Marker({
            position: new AMap.LngLat(markerData.lonGd, markerData.latGd),
            offset: new AMap.Pixel(-24, -30),
            title: markerData.localName,
            icon: new AMap.Icon({
              size: new AMap.Size(24, 30),
              image: markerData.icon,
              imageSize: new AMap.Size(24, 30)
            }),
            label: {
              content: `<div style="
                display: inline-block;
                padding: 6px;
                background-color: rgba(175,255,98,1);
                border: 1px solid #c4ff77;
                color: #b02cff;
                font-size: 12px;
                min-width: fit-content;
                position: relative;
                ">${markerData.localName}</div>`,
              direction: 'top',
              offset: new AMap.Pixel(0, 0)
            }
          });
          // 创建信息窗体内容
          const infoContent = this.createInfoWindowContent(markerData)

          // 创建信息窗体
          const infoWindow = new AMap.InfoWindow({
            content: infoContent,
            isCustom: true,
            offset: new AMap.Pixel(0, -30),
            backgroundColor:'transparent',
            closeWhenClickMap: true
          })

          // 添加点击事件
          marker.on('click', () => {
            // 发出点击事件，只传递 id
            console.log('Marker clicked:', markerData);
            infoWindow.open(this.map, marker.getPosition())
            this.setSelect(markerData.id);
            EventBus.$emit('sent-device-id-to-right', markerData);
          });

          // 在标记点添加到地图后修改父元素样式
          marker.on('complete', () => {
            const labelDom = marker.getContentDom();
            if (labelDom) {
              const parentElement = labelDom.parentElement;
              if (parentElement && parentElement.classList.contains('amap-marker-label')) {
                parentElement.style.background = 'none';
                parentElement.style.border = 'none';
                parentElement.style.padding = '0';
              }
            }
          });
          this.infoWindows.push(infoWindow);
          this.markerList.push(marker);
        });

        // 添加所有标注到地图
        if (this.markerList.length > 0) {
          this.map.add(this.markerList);
          // 等待标记点渲染完成后更新样式
          this.$nextTick(() => {
            this.updateMarkerStyles();
          });
        }
      },
      deep: true
    }
  },
  mounted() {
    this.initMap();
    // 每10秒创建一个弹窗
    setInterval(this.createRandomPopup, 6000);
  },
  methods: {
    // 更新图例
    initLegend(colorLegend,max) {
      this.heatLegend=[];
      if(colorLegend){
        const keys = Object.keys(colorLegend);
        keys.sort(function(a, b) {
          return parseFloat(a) - parseFloat(b); // 升序
        });
        var lastName=0;
        keys.forEach(key => {
          this.heatLegend.push({name:Number((lastName*max).toFixed(0))+'~'+Number((key*max).toFixed(0)),color:colorLegend[key]});
          lastName=parseFloat(key);
        });
      }
    },
    //最新数据展示
    createRandomPopup() {
      console.log(this.$route.path)
      if(this.identifyImageList.length==0 || this.$route.path!='/'){
        return;
      }

      var item=this.identifyImageList[0];
      if(this.identifyList&&this.identifyList.length>0){
        for (let i = 0; i < this.identifyList.length; i++) {
          if(this.identifyList[i].getPosition().lng==item.lon_gd&&this.identifyList[i].getPosition().lat==item.lat_gd){
            console.log(this.identifyList[i].getPosition());
            return;
          }
        }
      }
      // 获取地图边界
      const bounds = this.map.getBounds();
      const southWest = bounds.getSouthWest();
      const northEast = bounds.getNorthEast();

      // 计算随机位置
      const lng = southWest.lng + (northEast.lng - southWest.lng)*0.3 + Math.random() * (northEast.lng - southWest.lng)*0.4;
      const lat = southWest.lat + (northEast.lat - southWest.lat)*0.2 + Math.random() * (northEast.lat - southWest.lat)*0.4;

      // // 随机选择一张图片
      const content = document.createElement('div');
      content.className = 'marker-content';

      // 创建弹窗元素
      const popup = document.createElement('div');
      popup.className = 'image-popup';

      if(item.type=="video"){
        const url=item.video;
        popup.innerHTML = `<video class="content-video"
                   controls="false" autoplay loop
                   src="${url}"
                   controlsList="nodownload"
                   preload="auto"
            >
              您的浏览器不支持 video 标签。
            </video>`;
      }else {
        const url=item.image;
        popup.innerHTML = `<img src="${url}" alt="">`;
      }
      const speciesName = document.createElement('div');
      speciesName.className = 'species-name';
      speciesName.innerHTML = item.name;
      popup.appendChild(speciesName);
      const deviceName = document.createElement('div');
      deviceName.className = 'popup-device-name';
      deviceName.innerHTML = item.device_name;
      popup.appendChild(deviceName);
      content.appendChild(popup);
      const marker = new AMap.Marker({
        content: content, //自定义点标记覆盖物内容
        position: [item.lon_gd, item.lat_gd], //基点位置
        offset: new AMap.Pixel(-50, -50), // 居中显示
        zIndex: 100
      });
      this.map.add(marker);
      this.identifyList.push(marker);
      this.identifyImageList.splice(0, 1);
      // 设置关闭定时器
      let timeout = 15000; // 10秒
      let timer = setTimeout(() => {
        this.closePopup(marker);
        // this.map.remove(marker);
      }, timeout);

// 点击事件
      popup.addEventListener('click', () => {
        // 清除原有定时器
        clearTimeout(timer);

        // 切换大小
        popup.classList.toggle('enlarged');
        speciesName.classList.toggle('enlarged');
        deviceName.classList.toggle('enlarged');
        // 调整标记点偏移量
        const isEnlarged = popup.classList.contains('enlarged');
        marker.setOffset(new AMap.Pixel(isEnlarged ? -100 : -50, isEnlarged ? -100 : -50));
        marker._opts.zIndex+=1;
        // 增加停留时间
        timeout += 12000;

        // 重新设置定时器
        timer = setTimeout(() => {
          this.closePopup(marker);
        }, timeout);
      });
      //
      // // 存储弹窗引用
      // this.popups.push({
      //   element: popup,
      //   timer: timer
      // });
    },
    //最新数据展示
    showRarePlant(dataList) {
      this.rarePlantZIndex=1;
      if(this.rarePlantList&&this.rarePlantList.length>0){
        this.map.remove(this.rarePlantList);
        this.rarePlantList=[];
      }
      if(dataList==null||dataList.length==0){
        return;
      }

      for (let i = 0; i < dataList.length; i++) {
        var item=dataList[i];
        // // 随机选择一张图片
        const content = document.createElement('div');
        content.className = 'marker-content';

        // 创建弹窗元素
        const popup = document.createElement('div');
        popup.className = 'image-popup';

        if(item.type=="video"){
          const url=this.imgUrl+item.localPhoto;
          popup.innerHTML = `<video class="content-video"
                   controls="false" autoplay loop
                   src="${url}"
                   controlsList="nodownload"
                   preload="auto"
            >
              您的浏览器不支持 video 标签。
            </video>`;
        }else {
          const url=this.imgUrl+item.localPhoto;
          popup.innerHTML = `<img src="${url}" alt="">`;
        }
        const speciesName = document.createElement('div');
        speciesName.className = 'species-name';
        speciesName.innerHTML = item.localName;
        popup.appendChild(speciesName);
        const deviceName = document.createElement('div');
        deviceName.className = 'popup-device-name';
        deviceName.innerHTML = item.description;
        popup.appendChild(deviceName);
        content.appendChild(popup);
        const marker = new AMap.Marker({
          content: content, //自定义点标记覆盖物内容
          position: [item.lonGd, item.latGd], //基点位置
          offset: new AMap.Pixel(-50, -50), // 居中显示
          zIndex: 100
        });
        this.map.add(marker);
        this.rarePlantList.push(marker);
// 点击事件
        popup.addEventListener('click', () => {
          // 切换大小
          that.rarePlantZIndex++;
          marker._opts.zIndex=100+that.rarePlantZIndex;
          popup.classList.toggle('enlarged');
          speciesName.classList.toggle('enlarged');
          deviceName.classList.toggle('enlarged');
          // 调整标记点偏移量
          const isEnlarged = popup.classList.contains('enlarged');
          marker.setOffset(new AMap.Pixel(isEnlarged ? -100 : -50, isEnlarged ? -100 : -50));
          // 增加停留时间
        });
      }

    },
    clearIdentify(){
      this.map.remove(this.identifyList);
      while (this.identifyList.length>0){
        this.identifyList.pop();
      }
    },
    closePopup(marker) {
      // 获取弹窗元素
      const popup = marker.getContent().querySelector('.image-popup');

      // 添加消失动画
      popup.style.animation = 'popupDisappear 0.5s ease-in forwards';

      // 动画结束后移除标记点
      setTimeout(() => {
        this.map.remove(marker);

        // 从数组中移除
        const index = this.identifyList.findIndex(m => m === marker);
        if (index !== -1) {
          this.identifyList.splice(index, 1);
        }
      }, 500);
    },
    setMapPosition(p){
      if(this.map){
        var position = new AMap.LngLat(p.lon,p.lat); //传入经纬度
        this.map.setCenter(position); //简写 设置地图中心点
        this.map.setZoom(p.zoom);
      }
    },
    addPolygon(polygons){
      if (!this.map) return;
      if (!polygons&&polygons.length==0) return;
      // 清除现有标注
      if (this.polygonList.length > 0) {
        this.map.remove(this.polygonList);
      }
      if (this.textList.length > 0) {
        this.map.remove(this.textList);
      }
      this.polygonList=[];
      this.textList=[];
      for (let i = 0; i < polygons.length; i++) {
        var p=polygons[i];
        if(p&&p.polygon){
          var lo =[0,0];
          for (let j = 0; j < p.polygon.length; j++) {
            lo[0]=p.polygon[j][0]+lo[0];
            lo[1]=p.polygon[j][1]+lo[1];
          }
          lo=[lo[0]/p.polygon.length,lo[1]/p.polygon.length];
          // 创建多边形
          let polygon = new AMap.Polygon({
            path: p.polygon, // 多边形的顶点坐标数组
            fillColor: '#d523eb',
            strokeOpacity: 1,
            fillOpacity: 0.5,
            strokeColor: '#2b8cbe',
            strokeWeight: 1,
            strokeStyle: 'dashed',
            strokeDasharray: [5, 5],
          });
          //鼠标移入更改样式
          polygon.on('mouseover', () => {
            polygon.setOptions({
              fillOpacity: 0.7,
              fillColor: '#7bccc4'
            })
          })
          polygon.on('mouseout', () => {
            polygon.setOptions({
              fillOpacity: 0.5,
              fillColor: '#d523eb'
            })
          })
          // 将多边形添加到地图上
          this.map.add(polygon);
          this.polygonList.push(polygon);
          // 添加文本
          var text = new AMap.Text({
            text: p.localName, // 文本内容
            position: lo, // 文本位置，通常与多边形的中心点相同
            offset: new AMap.Pixel(-25, -40),
            style: {
              "padding": "6px",
              "background-color": "rgba(175,255,98,1)",
              "border": "1px solid #c4ff77",
              "color": "#b02cff",
              "font-size": "12px",
              "min-width": "fit-content",
              "position": "relative"
            }
          });
          // 将文本添加到地图上
          this.map.add(text);
          this.textList.push(text);
        }
      }
    },
    addMarkers(newMarkers){
      if (!this.map) return;

      // 清除现有标注
      if (this.markerList.length > 0) {
        this.map.remove(this.markerList);
      }
      if (this.infoWindows.length > 0) {
        this.infoWindows.forEach(function(currentValue, index) {
          if(currentValue.getIsOpen()){
            currentValue.close();
          }
        });
      }
      this.markerList = [];
      this.infoWindows=[];
      this.deviceList = newMarkers;
      // 添加新标注
      newMarkers.forEach(markerData => {
        const marker = new AMap.Marker({
          position: new AMap.LngLat(markerData.lonGd, markerData.latGd),
          offset: new AMap.Pixel(-12, -30),
          title: markerData.localName,
          icon: new AMap.Icon({
            size: new AMap.Size(24, 30),
            image: markerData.icon,
            imageSize: new AMap.Size(24, 30)
          }),
          label: {
            content: `<div style="
                display: inline-block;
                padding: 6px;
                background-color: rgba(175,255,98,1);
                border: 1px solid #c4ff77;
                color: #b02cff;
                font-size: 12px;
                min-width: fit-content;
                position: relative;
                ">${markerData.localName}</div>`,
            direction: 'top',
            offset: new AMap.Pixel(0, 0)
          }
        });
        // 创建信息窗体内容
        const infoContent = this.createInfoWindowContent(markerData)

        // 创建信息窗体
        const infoWindow = new AMap.InfoWindow({
          content: infoContent,
          isCustom: true,
          offset: new AMap.Pixel(0, -30),
          backgroundColor:'transparent',
          closeWhenClickMap: true
        })
        // 添加点击事件
        marker.on('click', () => {
          // 发出点击事件，只传递 id
          console.log('Marker clicked:', markerData);
          // this.$emit('marker-click', { id: markerData.id });
          infoWindow.open(this.map, marker.getPosition())
          this.setSelect(markerData.id);
          EventBus.$emit('sent-device-id-to-right', markerData);
        });
        // 监听鼠标划过事件并修改图标大小
        // marker.on('mouseover', (e) => {
        //   this.updateMarkerSize(e.target, 36, 45, -18, -22.5); // 放大图标大小，例如放大到60px
        // });

        // marker.on('mouseout', (e) => {
        //   this.updateMarkerSize(e.target, 24, 30, 0, 0); // 恢复图标大小，例如恢复到30px
        // });
        // 在标记点添加到地图后修改父元素样式
        marker.on('complete', () => {
          const labelDom = marker.getContentDom();
          if (labelDom) {
            const parentElement = labelDom.parentElement;
            if (parentElement && parentElement.classList.contains('amap-marker-label')) {
              parentElement.style.background = 'none';
              parentElement.style.border = 'none';
              parentElement.style.padding = '0';
            }
          }
        });

        this.markerList.push(marker);
        this.infoWindows.push(infoWindow);
      });

      // 添加所有标注到地图
      if (this.markerList.length > 0) {
        this.map.add(this.markerList);
        // 等待标记点渲染完成后更新样式
        this.$nextTick(() => {
          this.updateMarkerStyles();
        });
      }
    },
    setSelect(deviceId){
      if(this.markerList&&deviceId){
        for (let i = 0; i <this.deviceList.length ; i++) {
          if(deviceId==this.deviceList[i].id){
            this.updateMarkerSize(this.markerList[i],36,45,-36,-45);
            // this.setMapPosition({lon:this.deviceList[i].lonGd,lat:this.deviceList[i].latGd,zoom:17.5})
          }else {
            this.updateMarkerSize(this.markerList[i],24,30,-24,-30);
          }
        }
      }
    },
    updateMarkerSize(marker, sizeWidth, sizeHeight, offsetX, offsetY) {
      // 获取当前图标的图片URL
      const currentIcon = marker.getIcon();
      const imageUrl = currentIcon ? currentIcon._opts.image : null;
      const icon = new AMap.Icon({
        size: new AMap.Size(sizeWidth, sizeHeight), // 设置图标大小
        imageSize: new AMap.Size(sizeWidth, sizeHeight), // 设置图片大小，与图标大小一致
        image: imageUrl, // 使用原始图片URL
        offset: new AMap.Pixel(offsetX, offsetY)
      });
      marker.setIcon(icon); // 应用新的图标设置到标记点上
    },
    updateMarkerStyles() {
      // 查找所有标记点标签并更新样式
      const labels = document.getElementsByClassName('amap-marker-label');
      for (let label of labels) {
        label.style.background = 'none';
        label.style.border = 'none';
        label.style.padding = '0';
      }
    },
    updateLines(lines){
      if(this.polylines&&this.polylines.length>0){
        that.map.remove(this.polylines)
      }
      this.polylines=[];
      if(lines&&lines.length>0){
        for (let i = 0; i < lines.length; i++) {
          var polyline = new AMap.Polyline({
            path: lines[i].line,
            strokeWeight: lines[i].strokeWeight?lines[i].strokeWeight:4, //线条宽度
            strokeColor: lines[i].strokeColor?lines[i].strokeColor:'#C0C0C0', //线条颜色
            lineJoin: "round", //折线拐点连接处样式
          });
          this.map.add(polyline);
          this.polylines.push(polyline);
        }
      }
    },
    async initMap() {
      try {
        window._AMapSecurityConfig = {
          securityJsCode:'d3f358a71b15da54a12bfa500dcf7bc1',
        }

        if(this.map){
          return ;
        }
        AMapLoader.load({
          key: '5e8774fd0e150189b1fceec9a372fd1f',
          version: '2.0'
          // plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.Zoom', 'AMap.Pan']
        }).then((AMap) => {
          //JS API 加载完成后获取AMap对象
          // var imageLayer = new AMap.ImageLayer({
          //   url: 'http://111.229.223.177:9098/bg.png',
          //   bounds: new AMap.Bounds(
          //           [121.438105,31.152583],
          //           [121.450701,31.142331]
          //   ),
          //   zooms: [16, 19]
          // });
          this.map = new AMap.Map(this.$refs.mapContainer, {
            zoom:16.35,
            zooms: [16, 19],
            center: [121.444515, 31.145246],
            layers: [
              AMap.createDefaultLayer(),
               // imageLayer,
            ],
            optimizePanAnimation: true,
            WebGLParams: {
              alpha: false,
              antialias: false,
              stencil: false
            },
            mapStyle:'amap://styles/0a863b0cbc328c7e523ec2cd6df93523',
            viewMode: '2D',
            pitch: 30,
            dragEnable: true,
            zoomEnable: true,
            doubleClickZoom: true,
            scrollWheel: true,
            touchZoom: true,
            jogEnable: true,
            animateEnable: true,
            resizeEnable: true,
            features: ['bg', 'road', 'point'] , // 只显示背景、道路和建筑，不显示文字标注
            showLabel: false  // 关闭地图文字标注
          })

          const bounds=new AMap.Bounds(
                  [121.425355,31.129187], // 西南角坐标
                  [121.464388,31.165586]   // 东北角坐标
          );
          this.map.setLimitBounds(bounds);
          const pathArr = [
            [
              [
                [121.417081,31.164547],
                [121.409709,31.129703],
                [121.482508,31.129344],
                [121.479157,31.163328]
              ],
              [
                [121.450101,31.152033],
                [121.446793,31.151404],
                [121.446369,31.152372],
                [121.4408,31.150872],
                [121.441846,31.148162],
                [121.438058,31.147799],
                [121.438171,31.14734],
                [121.438143,31.143928],
                [121.438595,31.142404],
                [121.443797,31.143009],
                [121.443684,31.14342],
                [121.445097,31.143832],
                [121.444786,31.144606],
                [121.450412,31.146178],
              ],
            ],
          ];
          const polygon = new AMap.Polygon({
            path: pathArr, //多边形路径
            fillColor: "#000000", //多边形填充颜色
            strokeOpacity: 0, //线条透明度
            fillOpacity: 0.5, //填充透明度
            strokeColor: "#0038E3", //线条颜色
            strokeWeight: 2, //线条宽度
            strokeStyle: "dashed", //线样式
            strokeDasharray: [5, 5], //轮廓的虚线和间隙的样式
          });
          // this.map.add(polygon);
          this.$store.commit('setMapData', pathArr);
          this.map.plugin(["AMap.HeatMap"], function () {

            that.heatmap = new AMap.HeatMap(that.map, {
              radius: 40,
              opacity: [0, 0.8]
            });
            // resolve();
          });
          //切片地图
          var layer = new AMap.TileLayer.Flexible({
            cacheSize: 35,
            opacity: 1,
            createTile: function (x, y, z, success, fail) {
              var img = document.createElement('img');
              img.onload = function () {
                success(img)
              };
              img.crossOrigin = "anonymous";// 必须添加，同时图片要有跨域头
              img.onerror = function () {
                fail()
              };
              img.src = 'http://111.229.223.177:8090/renren-admin/api/bg/getLayer?x='+x+'&y='+y+'&z='+z;
            }
          });
          this.map.addLayer(layer);

          this.map.on('webglcontextlost', function() {
            console.log('Context lost, attempting to restore');
            // 这里可以尝试恢复或重新创建地图
          });

          setTimeout(() => {
            this.doorList.forEach(markerData => {
              const marker = new AMap.Marker({
                position: new AMap.LngLat(markerData.lonGd, markerData.latGd),
                offset: new AMap.Pixel(-24, -30),
                title: markerData.localName,
                icon: new AMap.Icon({
                  size: new AMap.Size(24, 30),
                  image: markerData.icon,
                  imageSize: new AMap.Size(24, 30)
                }),
                label: {
                  //border: 1px solid #19DCFF;
                  //background-color: rgba(25, 220, 255, 0.3);
                  content: `<div style="
                display: inline-block;
                padding: 6px;
                color: #beff18;
                font-size: 12px;
                min-width: fit-content;
                position: relative;
                ">${markerData.localName}</div>`,
                  direction: 'top',
                  offset: new AMap.Pixel(0, 0)
                }
              });
              this.map.add(marker);
            })
            this.$nextTick(() => {
              this.updateMarkerStyles();
            });
          }, 2000);

        }).catch((e) => {
          console.error(e); //加载错误提示
        });
      } catch (e) {
        console.error('地图加载失败：', e)
      }
    },
    addMarkersWithOutTitle(newMarkers){
      if (!this.map) return;

      // 清除现有标注
      if (this.markerList.length > 0) {
        this.map.remove(this.markerList);
      }
      if (this.infoWindows.length > 0) {
        this.infoWindows.forEach(function(currentValue, index) {
          if(currentValue.getIsOpen()){
            currentValue.close();
          }
        });
      }
      this.markerList = [];
      this.infoWindows=[];
      this.deviceList = newMarkers;
      // 添加新标注
      newMarkers.forEach(markerData => {
        const marker = new AMap.Marker({
          position: new AMap.LngLat(markerData.lonGd, markerData.latGd),
          offset: new AMap.Pixel(0, 0),
          title: markerData.localName,
          icon: new AMap.Icon({
            size: new AMap.Size(20, 20),
            image: markerData.icon,
            imageSize: new AMap.Size(20, 20)
          })
        });
        // 创建信息窗体内容
        const infoContent = this.createInfoWindowContent(markerData)

        // 创建信息窗体
        const infoWindow = new AMap.InfoWindow({
          content: infoContent,
          isCustom: true,
          offset: new AMap.Pixel(0, -30),
          backgroundColor:'transparent',
          closeWhenClickMap: true
        })
        // 添加点击事件
        marker.on('click', () => {
          // 发出点击事件，只传递 id
          console.log('Marker clicked:', markerData);
          // this.$emit('marker-click', { id: markerData.id });
          // infoWindow.open(this.map, marker.getPosition());
          EventBus.$emit('sent-registration', markerData);
        });
        // 监听鼠标划过事件并修改图标大小
        // marker.on('mouseover', (e) => {
        //   this.updateMarkerSize(e.target, 36, 45, -18, -22.5); // 放大图标大小，例如放大到60px
        // });

        // marker.on('mouseout', (e) => {
        //   this.updateMarkerSize(e.target, 24, 30, 0, 0); // 恢复图标大小，例如恢复到30px
        // });
        // 在标记点添加到地图后修改父元素样式
        marker.on('complete', () => {
          const labelDom = marker.getContentDom();
          if (labelDom) {
            const parentElement = labelDom.parentElement;
            if (parentElement && parentElement.classList.contains('amap-marker-label')) {
              parentElement.style.background = 'none';
              parentElement.style.border = 'none';
              parentElement.style.padding = '0';
            }
          }
        });

        this.markerList.push(marker);
        this.infoWindows.push(infoWindow);
      });

      // 添加所有标注到地图
      if (this.markerList.length > 0) {
        this.map.add(this.markerList);
        // 等待标记点渲染完成后更新样式
        this.$nextTick(() => {
          this.updateMarkerStyles();
        });
      }
    },
    createInfoWindowContent(location) {
      const container = document.createElement('div');
      const url=location.localPhoto?this.imgUrl+location.localPhoto.split(',')[0]:"";
      const visiable=location.localPhoto?true:false;
      container.className = 'custom-info-window'
      container.innerHTML = `
    <div class="data-point data-point-1"></div>
    <div class="data-point data-point-2"></div>
    <div class="data-point data-point-3"></div>
    <div class="data-point data-point-4"></div>
    <div class="info-header">
      <h3>${location.localName}</h3>
      <span class="info-title">${location.localName}</span>
    </div>
    <div class="info-body">
      <img v-if="${visiable}" src="${url}" alt="${location.localName}" class="info-image">
    </div>
  `
      return container
    }
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
      this.map=null;
    }
  }
}
</script>

<style>
  .ledgend-heat-item-text{
    width: 100px;
    height: 30px;
    line-height: 30px;
    text-align: center;
  }
  .ledgend-heat{
    position: absolute;
    bottom: 72px;
    right: 530px;
    z-index: 200;
  }
  .species-name {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
    color: white;
    text-align: center;
    padding: 4px 0;
    font-size: 12px;
    font-family: Arial, sans-serif;
    opacity: 0;
  }
  .species-name.enlarged{
    opacity: 1;
  }
  .popup-device-name {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    color: #ff9b17;
    text-align: center;
    padding: 4px 0;
    font-size: 12px;
    font-family: Arial, sans-serif;
    opacity: 0;
  }
  .popup-device-name.enlarged{
    opacity: 1;
  }
  .content-video::-webkit-media-controls {
    display: none; /* Chrome, Safari, Opera */
  }

  .content-video::-webkit-media-controls-panel {
    display: none; /* Chrome, Safari, Opera */
  }

  .content-video::-webkit-media-controls-play-button {
    display: none; /* Chrome, Safari, Opera */
  }

  .content-video::-webkit-media-controls-timeline {
    display: none; /* Chrome, Safari, Opera */
  }
  .image-popup {
    position: absolute;
    width: 100px;
    height: 100px;
    transform: translate(-50%, -50%);
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    animation: popupAppear 0.5s ease-out, borderGlow 2s linear infinite;
    z-index: 100;
    cursor: pointer;
    transition: all 0.3s ease;
  }
  /*.image-popup:hover {*/
  /*  transform: scale(1.5); !* 放大1.2倍 *!*/
  /*  z-index: 200;*/
  /*}*/
  .image-popup.enlarged {
    width: 300px;
    height: 300px;
  }

  .image-popup img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .image-popup video {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  @keyframes popupAppear {
    0% {
      transform: translate(-50%, -50%) scale(0.1) rotate(0deg);
      opacity: 0;
    }
    100% {
      transform: translate(-50%, -50%) scale(1) rotate(360deg);
      opacity: 1;
    }
  }

  @keyframes popupDisappear {
    0% {
      transform: translate(-50%, -50%) scale(1) rotate(0deg);
      opacity: 1;
    }
    100% {
      transform: translate(-50%, -50%) scale(0.1) rotate(360deg);
      opacity: 0;
    }
  }

  @keyframes borderGlow {
    0% {
      box-shadow: 0 0 5px #00ff00, 0 0 10px #00ff00;
    }
    25% {
      box-shadow: 0 0 5px #00ff00, 0 0 10px #00ff00, 0 0 15px #00ff00;
    }
    50% {
      box-shadow: 0 0 10px #00ff00, 0 0 15px #00ff00, 0 0 20px #00ff00;
    }
    75% {
      box-shadow: 0 0 5px #00ff00, 0 0 10px #00ff00, 0 0 15px #00ff00;
    }
    100% {
      box-shadow: 0 0 5px #00ff00, 0 0 10px #00ff00;
    }
  }

  /* 科技风信息窗体样式 */
  .custom-info-window {
    width: 300px;
    padding: 0;
    font-family: 'Arial', sans-serif;
    color: #e0e0e0;
    border-radius: 4px;
    background: rgba(10, 25, 47, 0.9);
    border: none !important;
    box-shadow: 0 0 15px rgba(0, 150, 255, 0.6);
    border: 1px solid rgba(0, 150, 255, 0.4);
    overflow: hidden;
    position: relative;
  }

  .custom-info-window::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent, rgba(0, 200, 255, 0.8), transparent);
    animation: scanline 3s linear infinite;
  }

  @keyframes scanline {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(100%); }
  }

  .custom-info-window .info-header {
    padding: 15px 15px 10px;
    background: rgba(0, 50, 90, 0.4);
    border-bottom: 1px solid rgba(0, 150, 255, 0.3);
    position: relative;
  }

  .custom-info-window .info-header h3 {
    margin: 0;
    font-size: 18px;
    color: #4fc3f7;
    font-weight: bold;
    text-shadow: 0 0 8px rgba(79, 195, 247, 0.4);
    letter-spacing: 1px;
  }

  .custom-info-window .info-title {
    display: block;
    font-size: 13px;
    color: #81d4fa;
    margin-top: 5px;
    font-family: 'Courier New', monospace;
  }

  .custom-info-window .info-body {
    padding: 15px;
  }

  .custom-info-window .info-image {
    width: 100%;
    height: 220px;
    object-fit: fill;
    margin-bottom: 15px;
    border: 1px solid rgba(0, 150, 255, 0.3);
    box-shadow: 0 0 10px rgba(0, 150, 255, 0.3);
  }

  .custom-info-window .info-description {
    margin: 0;
    font-size: 13px;
    line-height: 1.6;
    color: #b0bec5;
    font-family: 'Courier New', monospace;
  }

  /* 数据点装饰元素 */
  .data-point {
    position: absolute;
    width: 6px;
    height: 6px;
    background: rgba(0, 200, 255, 0.8);
    border-radius: 50%;
    box-shadow: 0 0 5px rgba(0, 200, 255, 0.8);
  }

  .data-point-1 { top: 10px; left: 10px; }
  .data-point-2 { top: 10px; right: 10px; }
  .data-point-3 { bottom: 10px; left: 10px; }
  .data-point-4 { bottom: 10px; right: 10px; }

  /* 隐藏高德默认样式 */
  .amap-info-outer,
  .amap-info-content,
  .amap-info-sharp {
    display: none !important;
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
  }
</style>